import {defineStore} from 'pinia'
import { userInfoLoginAPI } from '@/apis/userAPI'
import { ref } from 'vue'
import { useCartStore } from './cart'
import { mergeCartListAPI } from '@/apis/cartAPI'
import {getCartByUserIdAPI} from '@/apis/cartAPI'

export const useUserStore = defineStore('user',()=>{
    const cartStore = useCartStore();
    //1.定义管理用户数据的store
    const  userInfo = ref({})
    //2.获取接口数据的action
    const getUserInfo = async ({loginName,password}) => {
         //调用接口获取用户信息
            const res = await userInfoLoginAPI({loginName:loginName,password:password});
            userInfo.value = res.data

            // 给购物车每条数据增加userid字段
            if (Array.isArray(cartStore.cartList)) {
               cartStore.cartList.forEach(item => {
                  item.userId = res.data.userInfoVO.id
               })
            }
            await mergeCartListAPI(cartStore.cartList);
            const res2 = await getCartByUserIdAPI(res.data.userInfoVO.id);
            cartStore.setCartList(res2.data)

            // console.log(res.data);

            // console.log('test:', cartStore.cartList.value );


    }

    //2.1定义清除用户登录信息
    const clearUserInfo = () => {
       userInfo.value = {}
       cartStore.clearCart(); // 清空购物车列表
    }

    //3.以对象的方式把state和action返回
    return{
       userInfo,
       getUserInfo,
       clearUserInfo
    }
   }
  ,{
       persist:true
})
